import sys
import os
import re
import ConfigParser
import globalvar
from optparse import OptionParser
import shutil

def gen_fs_diff(orgfilename,targetfilename = None,newversionstr=None,vendor=None,withapp=False):
    (globalvar.OLD_VERSION,globalvar.NEW_VERSION,globalvar.MODEL,globalvar.VENDOR) = prepare_fs(orgfilename,targetfilename,newversionstr,vendor,withapp)
    globalvar.NEW_VERSION=globalvar.NEW_VERSION.strip() 
    config = ConfigParser.ConfigParser()
    config.read('products.ini')
    
    if globalvar.MODELNAME_IN_FILE == None:
        globalvar.MODELNAME_IN_FILE = globalvar.MODEL
        
    if withapp:
        shutil.copy("./CMCC_MENU_Update/OMS1.5/CMCCService.apk", "target/opl/etc/DM-Bigger.bin")
    fs_cmd=config.get(globalvar.MODEL,'fs_cmd')
    up_cmd = "%s %s-%s_fs_upgrade.bin source target "%(fs_cmd,globalvar.VENDOR,globalvar.MODELNAME_IN_FILE)        
    fd = os.popen(up_cmd)
    if globalvar.dmlogging:
        globalvar.dmlogging.debug('[%s]'%(up_cmd))
    fd.close()    


    up_cmd_debug ="vCurrentMobileCMD5.1.37.37.exe debug_trace %s-%s_fs_upgrade.bin %s-%s_fs_upgrade-debug.bin /setall=1"%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.VENDOR,globalvar.MODELNAME_IN_FILE)    
    fd = os.popen(up_cmd_debug)     
    if globalvar.dmlogging:
        globalvar.dmlogging.debug('[%s]'%(up_cmd_debug))
    fd.close()
            
    de_cmd = "%s %s-%s_fs_degrade.bin  target source"%(fs_cmd,globalvar.VENDOR,globalvar.MODELNAME_IN_FILE)
    fd = os.popen(de_cmd)
    if globalvar.dmlogging:
        globalvar.dmlogging.debug('[%s]'%(de_cmd))
    fd.close()
        
    de_cmd_debug ="vCurrentMobileCMD5.1.37.37.exe debug_trace %s-%s_fs_degrade.bin %s-%s_fs_degrade-debug.bin /setall=1"%(globalvar.VENDOR,globalvar.MODELNAME_IN_FILE,globalvar.VENDOR,globalvar.MODELNAME_IN_FILE)    
    fd = os.popen(de_cmd_debug)    
    if globalvar.dmlogging:
        globalvar.dmlogging.debug('[%s]'%(de_cmd_debug))
    fd.close()
        
    return 0
    
def prepare_fs(orgfilename,targetfilename=None,newversionstr=None,vendor=None,withapp=False):
    
    if os.path.isdir("source"):
        shutil.rmtree("source")
    if os.path.isdir("target"):        
        shutil.rmtree("target")

    ret = os.system("mkdir source\\opl\\etc")
    ret = os.system("mkdir target\\opl\\etc")
    

    fd = open(orgfilename,'r')    
    version_pattern = re.compile(r'apps.setting.product.release\s{0,}\=\s{0,}(.*)')
    model_pattern = re.compile(r'apps.setting.product.model\s{0,}\=\s{0,}(.*)')
    vendor_pattern = re.compile(r'apps.setting.product.vendor\s{0,}\=\s{0,}(.*)')
    all_str=fd.read()
    fd.close()

    result = version_pattern.findall(all_str)
    old_version = result[0]
    globalvar.OLD_VERSION = old_version
    result = model_pattern.findall(all_str)
    model =  result[0]
    result = vendor_pattern.findall(all_str)
    if vendor == None:
        vendor =  result[0]   
        vendor = vendor.strip() 
    if newversionstr:
        new_version =newversionstr 
    else:
        version_list = list(old_version)
        i = int(version_list[-1]) + 1
        version_list[-1] = str(i)
        new_version = "".join(["%s" % el for el in version_list])

    all_str= re.sub(version_pattern,'apps.setting.product.release=%s'%(new_version),all_str)
    t_fd = open('./target/opl/etc/system.prop','w')
    t_fd.write(all_str)
    t_fd.close()
    
    if orgfilename:
        shutil.copy(orgfilename,"source/opl/etc/system.prop")
    if targetfilename:
        shutil.copy(targetfilename,"target/opl/etc/system.prop")
    
                  
    return (old_version,new_version,model,vendor)

def main(*argv):
    """Generate the diff package using the """
    if argv:
        argv = list(argv)
    else:
        argv = sys.argv[1:]
        
    usage = "usage: fs_diff -i [infile]"    
    parser = OptionParser(usage=usage)    
    parser.add_option("-s", "--sourcefile", dest="sourcefile",type="string",help="source file ")
    parser.add_option("-t", "--targetfile", dest="targetfile",type="string",help="target file ")
    parser.add_option("-n", "--newversionstr", dest="newversionstr",type="string",help="new version str")
    parser.add_option("-v", "--vendor", dest="vendor",type="string",help="vendor str")
    newversionstr = vendor = targetfile = None
    (options, args) = parser.parse_args(args=argv)
    sourcefile = os.path.abspath(options.sourcefile)
    if(options.newversionstr):
        newversionstr =options.newversionstr
    if options.vendor:
        vendor = options.vendor
        
    if options.targetfile:
        targetfile = options.targetfile        
                
    ret = gen_fs_diff(sourcefile,targetfile,newversionstr,vendor)
    
        
if __name__ == "__main__":
    main()
    